package com.impetus.project.skilltest.db;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DataBaseConnection {
	private static Logger logger = Logger.getLogger(DataBaseConnection.class.getName());
	private Connection conn;
	private static DataBaseConnection connector;
	
	private String dbDriver;
	private String dbURL;
	private String dbUser;
	private String dbPassword;
	
	public DataBaseConnection() {
		Properties dbProps = new Properties();
		
		try{
			FileInputStream in = new FileInputStream("conf/Database_Properties.conf");
			dbProps.load(in);
			in.close();
		}catch(Exception e){
			logger.log(Level.SEVERE, "Exception occured while initializing db connector", e);
			e.printStackTrace();
		}
		
		dbDriver = dbProps.getProperty(DBConstants.DATABASE_DRIVER);
		dbURL = dbProps.getProperty(DBConstants.DATABASE_URL);
		dbUser = dbProps.getProperty(DBConstants.DATABASE_USER);
		dbPassword = dbProps.getProperty(DBConstants.DATABASE_PASSWORD);
	}
	
	public static Connection getConnection(){
		return connector.conn;
	}

	public boolean initialize(){
   	 boolean result = true;
   	 try {
   		 	@SuppressWarnings("unchecked")
			Class cls = Class.forName(dbDriver);
			DriverManager.registerDriver((Driver) cls.newInstance());
			String conStr = dbURL + "/" + dbUser + "/" + dbPassword;
			logger.info("Using connection string " + conStr);
			conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);
			conn.setAutoCommit(false);
			connector = this;
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Exception occured while initializing db connector", e);
			result = false;
		}
		return result;  
    }
}
